<template>
  <div class="community-container">
    <!-- 居中层叠轮播图 -->
    <div class="stack-carousel">
      <div 
        class="stack-item" 
        v-for="(img, index) in communityImages" 
        :key="index" 
        :style="{ 
          backgroundImage: `url(${img.purl || communityData.img})`,
          transform: `translateX(${(index - currentIndex) * 150}px) scale(${1 - Math.abs(index - currentIndex) * 0.05})`,
          zIndex: communityImages.length - Math.abs(index - currentIndex),
          opacity: Math.max(0.3, 1 - Math.abs(index - currentIndex) * 0.2)
        }"
        @click="currentIndex = index"
      >
        <div class="img-mask">
          <p>{{ img.name || `社区图片 ${index + 1}` }}</p>
        </div>
      </div>
    </div>

    <!-- 社区信息区域 -->
    <div class="community-info-section">
      <div class="community-address">
        <div class="info-left">
          <h2 class="community-name">{{ communityData.comName || '暂无社区名称' }}</h2>
          <div class="address-detail">
            <i class="location-icon">📍</i>
            <span v-if="communityData.address && communityData.address.length">
              {{ communityData.address[0].market || '' }}
              <span v-if="communityData.address[0].region"> {{ communityData.address[0].region }}</span>
              <span v-if="communityData.address[0].details"> {{ communityData.address[0].details }}</span>
            </span>
            <span v-else>暂无地址信息</span>
          </div>
        </div>
        
        <div class="info-right">
          <div class="contact-info">
            <p class="phone-label">咨询电话</p>
            <p class="phone-number">{{ communityData.phone || '暂无联系方式' }}</p>
          </div>
          <button class="route-btn" @click="showRouteDetails">
            路线详情 <i class="arrow-icon">→</i>
          </button>
        </div>
      </div>

      <!-- 社区介绍 -->
      <div class="community-description">
        <h3 class="desc-title">社区介绍</h3>
        <p class="desc-content">{{ communityData.describe || '暂无社区介绍信息' }}</p>
      </div>
    </div>

    <!-- 社区宿舍详情区域 -->
    <div class="community-detail">
      <h3>社区宿舍详情</h3>
      <div class="tab-container">
        <div class="tab-buttons">
          <div 
            class="tab-button" 
            :class="{ active: activeTab === 'dormitory' }"
            @click="activeTab = 'dormitory'"
          >
            宿舍信息
          </div>
          <div 
            class="tab-button" 
            :class="{ active: activeTab === 'comment' }"
            @click="activeTab = 'comment'"
          >
            评论
          </div>
        </div>
        
        <!-- 宿舍列表 -->
        <div v-if="activeTab === 'dormitory'" class="dormitory-list">
          <div class="dormitory-header">
            <div class="header-item">社区名称</div>
            <div class="header-item">楼层/门牌号</div>
            <div class="header-item">床位号</div>
            <div class="header-item">价格/月</div>
            <div class="header-item">入住人</div>
            <div class="header-item">入住时间</div>
            <div class="header-item">到期时间</div>
            <div class="header-item">操作</div>
          </div>
          
          <div class="dormitory-item" v-for="item in communityData.address" :key="item.addId">
            <div class="dormitory-cell">{{ communityData.comName }}</div>
            <div class="dormitory-cell">
              {{ item.floor }}楼/{{ item.number }}
            </div>
            <div class="dormitory-cell">{{ item.bed }}号床</div>
            <div class="dormitory-cell">¥{{ item.price.toFixed(2) }}</div>
            <div class="dormitory-cell">
              {{ formatUserName(item.user?.name) }}
            </div>
            <div class="dormitory-cell">
              {{ formatDate(item.checkInTime) }}
            </div>
            <div class="dormitory-cell">
              {{ formatDate(item.checkOutTime) }}
            </div>
            <div class="dormitory-cell">
              <button 
                class="apply-btn" 
                v-if="!item.user" 
                @click="openApplyModal(item)"
              >
                申请入住
              </button>
              <span v-else class="occupied">已入住</span>
            </div>
          </div>
        </div>
        
        <!-- 评论列表 -->
        <div v-if="activeTab === 'comment'" class="comment-list">
          <!-- 发布评论区域 -->
          <div class="comment-post-area">
            <button class="post-comment-btn" @click="showPostComment = !showPostComment">
              发布评论
            </button>
            
            <div class="comment-input-container" v-if="showPostComment">
              <textarea 
                v-model="newCommentContent" 
                class="comment-textarea"
                placeholder="分享您对这个社区的看法..."
                :rows="4"
              ></textarea>
              <div class="comment-actions">
                <button class="cancel-comment-btn" @click="showPostComment = false">取消</button>
                <button class="submit-comment-btn" @click="submitNewComment" :disabled="!newCommentContent.trim()">
                  发布
                </button>
              </div>
            </div>
          </div>
          
          <!-- 评论列表内容 -->
          <div class="comments-container">
            <!-- 顶级评论列表（parentId为null） -->
            <div class="comment-item" v-for="(comment, commentIndex) in showCommentData" :key="comment.commentId">
              <div class="comment-header">
                <!-- 评论用户头像 -->
                <div class="comment-avatar">
                  <img 
                    :src="comment.user?.img || defaultAvatar" 
                    :alt="comment.user?.name || '用户头像'"
                    class="avatar-img"
                  >
                  <span class="avatar-initial" v-if="!comment.user?.img">{{ getAvatarInitials(comment.user?.name) }}</span>
                </div>
                
                <div class="comment-user-info">
                  <div class="comment-username">{{ comment.user?.name || '匿名用户' }}</div>
                  <div class="comment-time">{{ formatDate(comment.createdAt) }}</div>
                </div>
              </div>
              
              <div class="comment-content">
                {{ comment.content }}
              </div>
              
              <div class="comment-actions">
                <button 
                  class="like-btn" 
                  @click="likeComment(commentIndex)"
                  :class="{ liked: comment.userLiked }"
                >
                  <i class="like-icon">{{ comment.userLiked ? '❤️' : '♡' }}</i>
                  <span class="likes-count">{{ comment.likesCount || 0 }}</span>
                </button>
                
                <button class="reply-btn" @click="toggleReplyInput(commentIndex, null, false, comment.commentId)">
                  回复
                </button>
              </div>
              
              <!-- 所有层级回复使用同一容器类 -->
              <div class="reply-container" v-if="comment.replies && comment.replies.length">
                <div class="reply-item" v-for="(reply, replyIndex) in comment.replies" :key="reply.commentId">
                  <div class="reply-avatar">
                    <img 
                      :src="reply.user?.img || defaultAvatar" 
                      :alt="reply.user?.name || '用户头像'"
                      class="avatar-img"
                    >
                    <span class="avatar-initial" v-if="!reply.user?.img">{{ getAvatarInitials(reply.user?.name) }}</span>
                  </div>
                  
                  <div class="reply-content">
                    <div class="reply-user-reference">
                      <span class="reply-username">{{ reply.user?.name || '匿名用户' }}</span>
                      <span class="reply-to"> 回复 </span>
                      <span class="reply-target-username">{{ reply.replyingToUser }}</span>
                    </div>
                    <div class="reply-text">{{ reply.content }}</div>
                    <div class="reply-time">{{ formatDate(reply.createdAt) }}</div>
                    
                    <div class="reply-actions">
                      <button 
                        class="reply-like-btn" 
                        @click="likeReply(commentIndex, replyIndex)"
                        :class="{ liked: reply.userLiked }"
                      >
                        <i class="like-icon">{{ reply.userLiked ? '❤️' : '♡' }}</i>
                        <span class="reply-likes-count">{{ reply.likesCount || 0 }}</span>
                      </button>
                      
                      <button class="reply-reply-btn" @click="toggleReplyInput(commentIndex, replyIndex, false, reply.commentId, reply.user?.name)">
                        回复
                      </button>
                    </div>
                    
                    <!-- 深层回复容器，复用同一类 -->
                    <div class="reply-container" v-if="reply.replies && reply.replies.length">
                      <recursive-replies 
                        :replies="reply.replies" 
                        :comment-index="commentIndex" 
                        :parent-reply-index="replyIndex"
                      />
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 回复输入框 -->
              <div class="reply-input-container" v-if="comment.showReplyInput">
                <div class="replying-to" v-if="comment.replyingToUser">
                  回复 {{ comment.replyingToUser }}:
                </div>
                <textarea 
                  v-model="comment.replyContent" 
                  class="reply-textarea"
                  placeholder="写下您的回复..."
                  :rows="2"
                ></textarea>
                <div class="reply-input-actions">
                  <button class="cancel-reply-btn" @click="toggleReplyInput(commentIndex, null, true)">
                    取消
                  </button>
                  <button 
                    class="submit-reply-btn" 
                    @click="submitReply(commentIndex, comment.replyingToId)"
                    :disabled="!comment.replyContent.trim()"
                  >
                    回复
                  </button>
                </div>
              </div>
            </div>
            
            <!-- 评论区占位 -->
            <div class="comment-placeholder" v-if="showCommentPlaceholder">
              暂无更多评论，成为第一个评论的人吧！
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 申请入住弹窗 -->
    <div v-if="applyModalVisible" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>申请入住</h3>
          <button class="close-btn" @click="closeApplyModal">×</button>
        </div>
        
        <div class="modal-body">
          <div class="form-group">
            <label>社区名称</label>
            <div class="form-value">{{ selectedDormitory?.comName || communityData.comName }}</div>
          </div>
          
          <div class="form-group">
            <label>房间号</label>
            <div class="form-value">{{ selectedDormitory?.floor }}楼{{ selectedDormitory?.number }} {{ selectedDormitory?.bed }}号床</div>
          </div>
          
          <div class="form-group">
            <label>申请人</label>
            <div class="form-value">{{ name }}</div>
          </div>
          
          <div class="form-group">
            <label>价格</label>
            <div class="form-value">¥{{ selectedDormitory?.price.toFixed(2) }}/月</div>
          </div>
          
          <div class="form-group">
            <label>起始时间</label>
            <input 
              type="date" 
              v-model="checkInDate" 
              :min="minCheckInDate"
              @change="calculateTotalPrice"
            >
          </div>
          
          <div class="form-group">
            <label>到期时间</label>
            <input 
              type="date" 
              v-model="checkOutDate" 
              :min="checkInDate"
              @change="calculateTotalPrice"
            >
          </div>
          
          <div class="form-group">
            <label>总价格</label>
            <div class="form-value price-total">¥{{ totalPrice.toFixed(2) }}</div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeApplyModal">取消</button>
          <button class="confirm-btn" @click="submitApplication" :disabled="!isFormValid">确定支付</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, defineComponent, h } from 'vue';
import { getCommunityImg, getCommunityById, getCommentsByCommunityId, insertComment, incrementLikesCount, decrementLikesCount, getUserLikeComment } from '@/api/communityDetail';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import { reactive } from 'vue';
import { alipay } from '@/api/food'; // 引入支付宝支付相关API
// 引入 uuid 函数（根据版本，可能是 v1、v4 等，v4 是随机 UUID 常用）
import { v4 as uuidv4 } from 'uuid';

// 递归回复组件（用于处理深层嵌套回复）
const RecursiveReplies = defineComponent({
  props: {
    replies: {
      type: Array,
      required: true
    },
    commentIndex: {
      type: Number,
      required: true
    },
    parentReplyIndex: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    // 生成头像首字母
    const getAvatarInitials = (userName) => {
      if (!userName) return '匿';
      return userName.charAt(0).toUpperCase();
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '暂无时间信息';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-');
    };
    
    return () => {
      return props.replies.map((reply, index) => {
        return h('div', { class: 'reply-item' }, [
          h('div', { class: 'reply-avatar' }, [
            reply.user?.img 
              ? h('img', { 
                  src: reply.user.img, 
                  alt: reply.user.name || '用户头像', 
                  class: 'avatar-img' 
                })
              : h('span', { class: 'avatar-initial' }, getAvatarInitials(reply.user?.name)),
          ]),
          h('div', { class: 'reply-content' }, [
            h('div', { class: 'reply-user-reference' }, [
              h('span', { class: 'reply-username' }, reply.user?.name || '匿名用户'),
              h('span', { class: 'reply-to' }, ' 回复 '),
              h('span', { class: 'reply-target-username' }, reply.replyingToUser || '匿名用户')
            ]),
            h('div', { class: 'reply-text' }, reply.content),
            h('div', { class: 'reply-time' }, formatDate(reply.createdAt)),
            h('div', { class: 'reply-actions' }, [
              h('button', { 
                class: ['reply-like-btn', reply.userLiked ? 'liked' : ''],
                onClick: () => {
                  // 触发父组件的点赞方法
                  likeNestedReply(props.commentIndex, props.parentReplyIndex, index);
                }
              }, [
                h('i', { class: 'like-icon' }, reply.userLiked ? '❤️' : '♡'),
                h('span', { class: 'reply-likes-count' }, reply.likesCount || 0)
              ]),
              h('button', { 
                class: 'reply-reply-btn',
                onClick: () => {
                  // 触发父组件的回复方法
                  toggleReplyInput(props.commentIndex, props.parentReplyIndex, index, reply.commentId, reply.user?.name);
                }
              }, '回复')
            ]),
            // 继续递归渲染更深层回复
            reply.replies && reply.replies.length 
              ? h('div', { class: 'reply-container' }, [
                  h(RecursiveReplies, {
                    replies: reply.replies,
                    commentIndex: props.commentIndex,
                    parentReplyIndex: props.parentReplyIndex
                  })
                ])
              : null
          ])
        ]);
      });
    };
  }
});

// 获取用户状态
const user = useUserStore();
const name = computed(() => user.currentUser?.name || '未登录用户');
const userId = computed(() => user.currentUser?.userId || '未登录用户ID');
const addId = ref(0);
// 默认头像
const defaultAvatar = null;

// 路由参数
const route = useRoute();
const comId = route.params.comId;
const router = useRouter();

// 社区图片轮播
const communityImages = ref([]);
const currentIndex = ref(0);

// 社区数据
const communityData = ref({});
const activeTab = ref('dormitory');

// 评论相关状态
const showCommentPlaceholder = ref(true);
const showCommentData = ref([]);
const newCommentContent = ref('');
const userLikeComment = ref([]);
const showPostComment = ref(false);

// 构建评论映射表，用于快速查找父评论信息（包括所有层级）
const buildCommentMap = (comments) => {
  const commentMap = {};
  
  // 递归处理所有层级评论（包括顶级评论、一级回复、二级回复等）
  const processComments = (commentList) => {
    if (!commentList || !commentList.length) return;
    
    commentList.forEach(comment => {
      // 存储当前评论的ID和对应的用户名（匿名用户兜底）
      commentMap[comment.commentId] = {
        userId: comment.userId,
        userName: comment.user?.name || '匿名用户' // 关键：记录被回复人的用户名
      };
      
      // 递归处理子评论（深层回复）
      if (comment.replies && comment.replies.length) {
        processComments(comment.replies);
      }
    });
  };
  
  processComments(comments);
  return commentMap;
};
// 初始化评论数据结构（适配后端字段并添加回复关系）
const initCommentDataStructure = (comments) => {
  // 构建所有评论的映射表（包括所有层级）
  const commentMap = buildCommentMap(comments);
  
  // 递归处理评论及其子评论
  const processComment = (comment) => {
    const commentMap = buildCommentMap(comments); // 获取所有评论的映射表
    // 基础结构
    const processedComment = {
      ...comment,
      showReplies: true, // 默认显示所有子评论
      showReplyInput: false,
      replyContent: '',
      replyingToId: null, // 被回复评论的ID
      replyingToUser: null, // 被回复用户的名称
      userLiked: false,
      replies: []
    };
    
    // 处理子评论
    // 处理子回复（重点：为回复设置“被回复人”信息）
    if (comment.replies && comment.replies.length) {
      processedComment.replies = comment.replies.map(reply => {
        // 通过回复的parentId，从映射表中找父评论（被回复的评论）的信息
        const parentInfo = commentMap[reply.parentId]; 
        return processComment({
          ...reply,
          // 关键：设置“被回复人”的用户名（父评论的用户名）
          replyingToUser: parentInfo ? parentInfo.userName : '未知用户' 
        });
      });
    }
    
    return processedComment;
  };
  
  // 只返回顶级评论（parentId为null的评论）
  return comments.filter(comment => comment.parentId === null).map(processComment);
};

// 生成头像首字母
const getAvatarInitials = (userName) => {
  if (!userName) return '匿';
  return userName.charAt(0).toUpperCase();
};

// 切换回复输入框显示/隐藏
const toggleReplyInput = (commentIndex, replyIndex, nestedIndex, replyingToId, replyingToUser, isCancel = false) => {
  const comment = showCommentData.value[commentIndex];
  
  if (isCancel) {
    comment.showReplyInput = false;
    comment.replyContent = '';
    comment.replyingToId = null;
    comment.replyingToUser = null;
    return;
  }
  
  // 先关闭所有评论的回复框
  showCommentData.value.forEach(item => {
    item.showReplyInput = false;
    item.replyContent = '';
    item.replyingToId = null;
    item.replyingToUser = null;
  });
  
  // 设置当前评论的回复信息
  comment.showReplyInput = true;
  comment.replyingToId = replyingToId;
  comment.replyingToUser = replyingToUser;
};

// 设置评论和回复的点赞状态
const setCommentLikeStatus = () => {
  // 递归设置点赞状态
  const setLikedStatus = (comments) => {
    if (!comments || !comments.length) return;
    
    comments.forEach(comment => {
      // 检查当前评论是否被当前用户点赞
      comment.userLiked = userLikeComment.value.some(like => 
        like.userId === userId.value && like.commentId === comment.commentId
      );
      
      // 递归处理子评论
      if (comment.replies && comment.replies.length) {
        setLikedStatus(comment.replies);
      }
    });
  };
  
  setLikedStatus(showCommentData.value);
};

// 点赞评论（顶级评论）
const likeComment = (commentIndex) => {
  const comment = showCommentData.value[commentIndex];
  const currentUserId = userId.value;
  
  if (comment.userLiked) {
    // 取消点赞
    comment.likesCount = Math.max(0, (comment.likesCount || 0) - 1);
    decrementLikesCount({ commentId: comment.commentId, userId: currentUserId }).then(res => {
      if (res.code !== 200) {
        console.error('取消点赞失败:', res.message);
      }
    }).catch(err => console.error('取消点赞请求失败:', err));
    
    // 从userLikeComment中移除该点赞记录
    userLikeComment.value = userLikeComment.value.filter(
      item => !(item.userId === currentUserId && item.commentId === comment.commentId)
    );
  } else {
    // 点赞
    comment.likesCount = (comment.likesCount || 0) + 1;
    incrementLikesCount({ commentId: comment.commentId, userId: currentUserId }).then(res => {
      if (res.code !== 200) {
        console.error('点赞失败:', res.message);
      }
    }).catch(err => console.error('点赞请求失败:', err));
    
    // 添加新的点赞记录到userLikeComment
    userLikeComment.value.push({
      likeId: Date.now(),
      userId: currentUserId,
      commentId: comment.commentId
    });
  }
  
  // 切换当前用户的点赞状态
  comment.userLiked = !comment.userLiked;
};

// 点赞一级回复
const likeReply = (commentIndex, replyIndex) => {
  const comment = showCommentData.value[commentIndex];
  const reply = comment.replies[replyIndex];
  const currentUserId = userId.value;
  
  if (reply.userLiked) {
    // 取消点赞
    reply.likesCount = Math.max(0, (reply.likesCount || 0) - 1);
    decrementLikesCount({ commentId: reply.commentId, userId: currentUserId }).then(res => {
      if (res.code !== 200) {
        console.error('取消点赞失败:', res.message);
      }
    }).catch(err => console.error('取消点赞请求失败:', err));
    
    // 从userLikeComment中移除该点赞记录
    userLikeComment.value = userLikeComment.value.filter(
      item => !(item.userId === currentUserId && item.commentId === reply.commentId)
    );
  } else {
    // 点赞
    reply.likesCount = (reply.likesCount || 0) + 1;
    incrementLikesCount({ commentId: reply.commentId, userId: currentUserId }).then(res => {
      if (res.code !== 200) {
        console.error('点赞失败:', res.message);
      }
    }).catch(err => console.error('点赞请求失败:', err));
    
    // 添加新的点赞记录到userLikeComment
    userLikeComment.value.push({
      likeId: Date.now(),
      userId: currentUserId,
      commentId: reply.commentId
    });
  }
  
  // 切换当前用户的点赞状态
  reply.userLiked = !reply.userLiked;
};

// 点赞嵌套回复（二级及以上回复）
const likeNestedReply = (commentIndex, replyIndex, nestedIndex) => {
  const comment = showCommentData.value[commentIndex];
  const reply = comment.replies[replyIndex];
  const nestedReply = reply.replies[nestedIndex];
  const currentUserId = userId.value;
  
  if (nestedReply.userLiked) {
    // 取消点赞
    nestedReply.likesCount = Math.max(0, (nestedReply.likesCount || 0) - 1);
    decrementLikesCount({ commentId: nestedReply.commentId, userId: currentUserId }).then(res => {
      if (res.code !== 200) {
        console.error('取消点赞失败:', res.message);
      }
    }).catch(err => console.error('取消点赞请求失败:', err));
    
    // 从userLikeComment中移除该点赞记录
    userLikeComment.value = userLikeComment.value.filter(
      item => !(item.userId === currentUserId && item.commentId === nestedReply.commentId)
    );
  } else {
    // 点赞
    nestedReply.likesCount = (nestedReply.likesCount || 0) + 1;
    incrementLikesCount({ commentId: nestedReply.commentId, userId: currentUserId }).then(res => {
      if (res.code !== 200) {
        console.error('点赞失败:', res.message);
      }
    }).catch(err => console.error('点赞请求失败:', err));
    
    // 添加新的点赞记录到userLikeComment
    userLikeComment.value.push({
      likeId: Date.now(),
      userId: currentUserId,
      commentId: nestedReply.commentId
    });
  }
  
  // 切换当前用户的点赞状态
  nestedReply.userLiked = !nestedReply.userLiked;
};

// 提交新评论（顶级评论）
const submitNewComment = () => {
  if (!newCommentContent.value.trim()) return;
  
  const newComment = {
    content: newCommentContent.value,
    userId: userId.value,
    comId: comId,
    parentId: null, // 顶级评论parentId为null
    likesCount: 0
  };
  
  insertComment(newComment).then(res => {
    if (res.code === 200) {
      getCommentsByCommunityId({ comId }).then(newComments => {
        showCommentData.value = initCommentDataStructure(newComments.data);
        showCommentPlaceholder.value = showCommentData.value.length === 0;
        setCommentLikeStatus();
      }).catch(err => console.error('获取评论失败:', err));
    } else {
      console.error('提交评论失败:', res.message);
    }
  }).catch(err => console.error('提交评论请求失败:', err));
  
  newCommentContent.value = '';
  showPostComment.value = false;
};

// 提交回复（支持回复任何层级的评论）
const submitReply = (commentIndex, parentId) => {
  const comment = showCommentData.value[commentIndex];
  if (!comment.replyContent.trim() || !parentId) return;
  
  const newReply = {
    content: comment.replyContent,
    likesCount: 0,
    comId: comId,
    userId: userId.value,
    parentId: parentId // 被回复评论的ID
  };
  
  insertComment(newReply).then(res => {
    if (res.code === 200) {
      getCommentsByCommunityId({ comId }).then(newReply => {
        showCommentData.value = initCommentDataStructure(newReply.data);
        showCommentPlaceholder.value = showCommentData.value.length === 0;
        setCommentLikeStatus();
      }).catch(err => console.error('获取评论失败:', err));
    } else {
      console.error('提交回复失败:', res.message);
    }
  }).catch(err => console.error('提交回复请求失败:', err));
  
  // 重置回复状态
  comment.replyContent = '';
  comment.showReplyInput = false;
  comment.replyingToId = null;
  comment.replyingToUser = null;
};

// 申请入住弹窗相关状态
const applyModalVisible = ref(false);
const selectedDormitory = ref(null);
const checkInDate = ref('');
const checkOutDate = ref('');
const totalPrice = ref(0);
const today = new Date();
const minCheckInDate = ref(today.toISOString().split('T')[0]);

// 打开申请入住弹窗
const openApplyModal = (item) => {
  selectedDormitory.value = item;
  addId.value = item.addId;
  checkInDate.value = minCheckInDate.value;
  checkOutDate.value = '';
  totalPrice.value = 0;
  applyModalVisible.value = true;
};

// 关闭申请入住弹窗
const closeApplyModal = () => {
  applyModalVisible.value = false;
  selectedDormitory.value = null;
};

// 计算总价格
const calculateTotalPrice = () => {
  if (!checkInDate.value || !checkOutDate.value || !selectedDormitory.value) {
    totalPrice.value = 0;
    return;
  }
  
  const startDate = new Date(checkInDate.value);
  const endDate = new Date(checkOutDate.value);
  
  // 计算月份差
  let months = (endDate.getFullYear() - startDate.getFullYear()) * 12;
  months += endDate.getMonth() - startDate.getMonth();
  
  // 计算剩余天数（不足一个月按一个月计算）
  const remainingDays = (endDate - new Date(startDate.getFullYear(), startDate.getMonth() + months, startDate.getDate())) / (1000 * 60 * 60 * 24);
  if (remainingDays > 0) {
    months += 1;
  }
  
  // 计算总价
  totalPrice.value = months * selectedDormitory.value.price;
};

// 表单验证
const isFormValid = computed(() => {
  return checkInDate.value && checkOutDate.value && 
         new Date(checkOutDate.value) > new Date(checkInDate.value) &&
         totalPrice.value > 0;
});
//封装支付信息
let payData = reactive({
  userId: userId.value,
  // 生成 UUID 作为订单号
  TradeNo: uuidv4(), 
  totalAmount: 0, 
  subject: '入住订单', 
  RETURN_URL: `http://localhost:8888/CommunityDetail/${comId}`, 
  // NOTIFY_URL: 'http://sde6ca78.natappfree.cc/api/community/notify',
   NOTIFY_URL: 'http://yeyyy.mynatapp.cc/api/community/notify',
});

// 提交申请
const submitApplication = () => {
  if (!isFormValid.value) return;
  let data1={
  checkInDate: checkInDate.value,
  checkOutDate: checkOutDate.value,
  addId: addId.value,
  userId: userId.value,
  }
  payData.body = Object.values(data1).join(',');
  payData.totalAmount = Number(totalPrice.value.toFixed(2));
  console.log('提交申请数据:', payData);
  alipay(payData).then(res => {
    if (res.code === 200) {
      const div = document.createElement('div');
   
      div.innerHTML = res.data;
      document.body.appendChild(div);
      //自动提交表单
      const form = div.querySelector('form');
      if (form) {
        form.submit();
      } else {
        console.error('支付表单未找到');
      }
      closeApplyModal();
    } else {
      console.error('支付失败:', res.message);
      alert('支付失败，请稍后再试。');
    }
  }).catch(err => {
    console.error('支付请求失败:', err);
    alert('支付请求失败，请稍后再试。');
  });
  console.log('提交申请:', {
    dormitory: selectedDormitory.value,
    checkInDate: checkInDate.value,
    checkOutDate: checkOutDate.value,
    totalPrice: totalPrice.value
  });
  
  // alert(`申请${selectedDormitory.value.floor}楼${selectedDormitory.value.number}${selectedDormitory.value.bed}号床成功！`);
  closeApplyModal();
};

// 页面加载时初始化数据
onMounted(() => {
  console.log('支付的数据', payData);
  // 获取社区图片
  getCommunityImg({ comId }).then(res => {
    if (res.code === 200) {
      communityImages.value = res.data;
    }
  }).catch(err => console.error('获取社区图片失败：', err));
  
  // 获取社区详情
  getCommunityById({ comId }).then(res => {
    if (res.code === 200) {
      communityData.value = res.data;
    }
  }).catch(err => console.error('获取社区详情失败：', err));
  
  // 获取评论数据
  getCommentsByCommunityId({ comId }).then(res => {
    if (res.code === 200) {
      // 只处理顶级评论（parentId为null的评论）
      showCommentData.value = initCommentDataStructure(res.data);
      showCommentPlaceholder.value = showCommentData.value.length === 0;
      
      if (userLikeComment.value.length > 0) {
        setCommentLikeStatus();
      }
    } else {
      console.error('获取评论失败:', res.message);
    }
  }).catch(err => console.error('获取评论请求失败:', err));
  
  // 获取用户点赞数据
  getUserLikeComment({ userId: userId.value }).then(res => {
    if (res.code === 200) {
      userLikeComment.value = res.data;
      
      if (showCommentData.value.length > 0) {
        setCommentLikeStatus();
      }
    } else {
      console.error('获取用户点赞数据失败:', res.message);
    }
  }).catch(err => console.error('获取用户点赞数据请求失败:', err));
});

// 格式化用户姓名
const formatUserName = (userName) => {
  if (!userName) return '暂无信息';
  return userName.length > 1 ? userName[0] + '**' : userName + '**';
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '暂无时间信息';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');
};

// 路线详情点击事件
const showRouteDetails = () => {
  router.push({ name: 'RouteDetails', params: { comId:comId } });
};
</script>

<style scoped>
/* 基础样式重置与全局设置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.community-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9fafb;
}

/* 轮播图区域样式 */
/* 轮播图样式 */
.stack-carousel {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 350px;
  width: 100%;
  overflow: hidden;
  padding: 15px 20px;
  position: relative;
  background-color: #f5f5f5;
  margin-bottom: 15px;
}

.stack-item {
  position: absolute;
  width: 680px;
  height: 320px;
  background-size: cover;
  background-position: center;
  border-radius: 12px;
  transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1);
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  display: flex;
  align-items: flex-end;
}

.img-mask {
  width: 100%;
  padding: 15px 20px;
  background: linear-gradient(to top, rgba(0,0,0,0.7), rgba(0,0,0,0));
  color: white;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.stack-item:hover .img-mask {
  opacity: 1;
}

.stack-item.current .img-mask {
  opacity: 1 !important;
}

.current {
  transform: translateX(0) scale(1);
  box-shadow: 0 10px 24px rgba(0,0,0,0.25);
  z-index: 100;
}

/* 社区信息区域样式 */
.community-info-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.community-address {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

/* 左侧地址信息 */
.info-left {
  flex: 1;
}

.community-name {
  font-size: 24px;
  color: #1a1a1a;
  margin-bottom: 12px;
  font-weight: 600;
}

.address-detail {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.location-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 右侧联系信息 */
.info-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 15px;
}

.contact-info {
  text-align: right;
}

.phone-label {
  color: #999;
  font-size: 13px;
  margin-bottom: 5px;
}

.phone-number {
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.route-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: background-color 0.2s;
}

.route-btn:hover {
  background-color: #3088e6;
}

.arrow-icon {
  font-size: 12px;
}

/* 社区介绍 */
.community-description {
  margin-top: 20px;
}

.desc-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.desc-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.desc-content {
  color: #666;
  line-height: 1.6;
  font-size: 14px;
  padding-left: 12px;
}

/* 社区宿舍详情区域 */
.community-detail {
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.community-detail h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

/* 标签切换容器 */
.tab-container {
  margin-top: 15px;
}

.tab-buttons {
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
}

.tab-button {
  padding: 10px 20px;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-button.active {
  color: #409eff;
  border-bottom-color: #409eff;
  font-weight: 500;
}

.tab-button:hover:not(.active) {
  color: #333;
  border-bottom-color: #eee;
}

/* 宿舍列表样式 */
.dormitory-list {
  width: 100%;
  border-collapse: collapse;
}

.dormitory-header {
  display: flex;
  background-color: #f5f7fa;
  border-radius: 6px 6px 0 0;
  overflow: hidden;
}

.header-item {
  flex: 1;
  padding: 12px 15px;
  font-size: 14px;
  color: #666;
  font-weight: 500;
  text-align: center;
  border-right: 1px solid #e5e5e5;
}

.header-item:last-child {
  border-right: none;
}

.dormitory-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e5e5e5;
  transition: background-color 0.1s;
}

.dormitory-item:hover {
  background-color: #fafafa;
}

.dormitory-cell {
  flex: 1;
  padding: 15px;
  font-size: 14px;
  color: #333;
  text-align: center;
}

.apply-btn {
  background-color: #52c41a;
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.apply-btn:hover {
  background-color: #47b814;
}

.occupied {
  color: #f5222d;
  font-size: 13px;
  background-color: #fff1f0;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 评论区域样式 */
.comment-list {
  margin-top: 10px;
}

/* 发布评论区域 */
.comment-post-area {
  margin-bottom: 30px;
}

.post-comment-btn {
  background-color: #f5f7fa;
  color: #409eff;
  border: 1px solid #e1e4e8;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.post-comment-btn:hover {
  background-color: #eef2f7;
}

.comment-input-container {
  margin-top: 15px;
  background-color: #fafafa;
  padding: 15px;
  border-radius: 6px;
}

.comment-textarea {
  width: 100%;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  padding: 10px;
  font-size: 14px;
  resize: none;
  transition: border-color 0.2s;
}

.comment-textarea:focus {
  outline: none;
  border-color: #409eff;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.cancel-comment-btn {
  background-color: #fff;
  color: #666;
  border: 1px solid #e5e5e5;
  padding: 6px 14px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-comment-btn:hover {
  background-color: #f5f5f5;
}

.submit-comment-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  padding: 6px 14px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-comment-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.submit-comment-btn:not(:disabled):hover {
  background-color: #3088e6;
}

/* 评论列表内容 */
.comments-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #e8f3ff;
  position: relative;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-initial {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.comment-user-info {
  display: flex;
  flex-direction: column;
}

.comment-username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.comment-time {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.comment-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 10px;
  padding-left: 50px; /* 与头像对齐 */
}

.comment-actions {
  display: flex;
  gap: 20px;
  padding-left: 50px; /* 与头像对齐 */
}

.like-btn, .reply-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: color 0.2s;
}

.like-btn:hover, .reply-btn:hover {
  color: #409eff;
}

.like-btn.liked {
  color: #f5222d;
}

.like-icon {
  font-size: 14px;
}

.likes-count {
  font-size: 12px;
}

/* 统一所有层级回复的容器样式 */
.reply-container {
  padding-left: 50px; /* 与顶级评论内容对齐 */
    margin: 10px 0;
}

.reply-item {
  display: flex;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f8f8f8;
}

.reply-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #e8f3ff;
  position: relative;
}

.reply-content {
  flex: 1;
}

.reply-user-reference {
  display: flex;
  align-items: center;
  font-size: 13px;
  margin-bottom: 5px;
}

.reply-username, .reply-target-username {
  color: #333;
  font-weight: 500;
}

.reply-to {
  color: #999;
  margin: 0 5px;
}

.reply-text {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 5px;
}

.reply-time {
  font-size: 11px;
  color: #999;
  margin-bottom: 5px;
}

.reply-actions {
  display: flex;
  gap: 15px;
  font-size: 12px;
}

.reply-like-btn, .reply-reply-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 3px;
  transition: color 0.2s;
}

.reply-like-btn:hover, .reply-reply-btn:hover {
  color: #409eff;
}

.reply-like-btn.liked {
  color: #f5222d;
}

.reply-likes-count {
  font-size: 11px;
}

/* 回复输入框 */
.reply-input-container {
  padding-left: 50px; /* 与头像对齐 */
  margin-top: 10px;
}

.replying-to {
  font-size: 13px;
  color: #999;
  margin-bottom: 5px;
}

.reply-textarea {
  width: 100%;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  padding: 8px 10px;
  font-size: 13px;
  resize: none;
  transition: border-color 0.2s;
}

.reply-textarea:focus {
  outline: none;
  border-color: #409eff;
}

.reply-input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 8px;
}

.cancel-reply-btn {
  background-color: #fff;
  color: #666;
  border: 1px solid #e5e5e5;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-reply-btn:hover {
  background-color: #f5f5f5;
}

.submit-reply-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-reply-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.submit-reply-btn:not(:disabled):hover {
  background-color: #3088e6;
}

/* 评论区占位 */
.comment-placeholder {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding: 20px 0;
}

/* 申请入住弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  width: 450px;
  max-width: 90%;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.3s ease-out;
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.form-value {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
}

.price-total {
  color: #f5222d;
  font-weight: 500;
}

.modal-body input[type="date"] {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  transition: border-color 0.2s;
}

.modal-body input[type="date"]:focus {
  outline: none;
  border-color: #409eff;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #e5e5e5;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  background-color: #fff;
  color: #666;
  border: 1px solid #e5e5e5;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
}

.confirm-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.confirm-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.confirm-btn:not(:disabled):hover {
  background-color: #3088e6;
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}
</style>